using UnityEngine;
using System.Collections;

// rung of ladder
public class LadderRung : MonoBehaviour 
{
	private const float Depth = -3f;
	private static int LastID = 0;
	
	private int m_id = -1;
	private Vector3[] m_points = null;
	
	private LineRenderer m_renderer = null;
	private Color m_color = Color.blue;
	private float m_width = 5f;
	
	public int ID 
	{ 
		get { return m_id; } 
	}
	
	public int FirstPointX
	{
		get { return (int)m_points[0].x; }
	}
	
	public int SecondPointX
	{
		get { return (int)m_points[1].x; }
	}
	
	public static LadderRung Create(Vector2 p1, Vector2 p2)
	{
		LastID++;
		GameObject ladderRungObj = new GameObject("LadderRung_" + LastID);
		LadderRung ladderRung = ladderRungObj.AddComponent<LadderRung>();
		ladderRung.Initialize(LastID, p1, p2);
		return ladderRung;
	}
	
	// Initialization
	private void Initialize (int id, Vector2 p1, Vector2 p2) 
	{
		m_id = id;
		m_points = new Vector3[2] { new Vector3(p1.x, p1.y, Depth), new Vector3(p2.x, p2.y, Depth) };
		
		m_renderer = GetComponent<LineRenderer>();
		if (m_renderer == null)
		{
			m_renderer = gameObject.AddComponent<LineRenderer>();
		}
		
		m_renderer.material = Material.Instantiate(Resources.Load("Materials/Column_Material")) as Material;
		m_renderer.SetColors(m_color, m_color);
		m_renderer.SetWidth(m_width, m_width);
		m_renderer.SetVertexCount(m_points.Length);
	}
	
	/*
	// When class instance started, Start is called.
	private void Start()
	{
		for (int i = 0; i < m_points.Length; ++i)
		{
			m_renderer.SetPosition(i, m_points[i]);
		}
	}
	*/
	
	// Update is called once per frame
	private void Update () 
	{
		for (int i = 0; i < m_points.Length; ++i)
		{
			m_renderer.SetPosition(i, m_points[i]);
		}
	}
	
	public bool TryGetPosY(int posX, out int posY)
	{
		posY = int.MinValue;
		
		for (int i = 0; i < m_points.Length; ++i)
		{
			if ((int)m_points[i].x == posX)
			{
				posY = (int)m_points[i].y;
				return true;
			}
		}
		
		return false;
	}
}

